// eslint-disable-next-line indent
const { Controller } = require('egg')
const { searchQuery, errorParams, checkSNExists } = require('../utils/tools');
const { typeOutput, excalOutput } = require('../utils/modelWarehousing');
const { mysqlName } = require("../utils/config")
const { omit } = require("loadsh")
const { MACHINE_WAREHOSING, MACHINE_MODEL, AGENCY } = mysqlName
const moment = require("moment")
const XLSX = require('xlsx');
class HomeController extends Controller {
    async getWarehousingList() {
        //机具入库查询--
        const { ctx } = this
        const body = ctx.request.body || {};
        const params = body.data || {}
        const pageInfo = body.pageInfo
        const tableName = MACHINE_WAREHOSING;
        const { sqlQuery, sqlCount } = searchQuery(tableName, params, pageInfo.pageNum, pageInfo.pageSize)
        const data = await ctx.app.mysql.query(sqlQuery)
        const modelSql = searchQuery(MACHINE_MODEL, {}, 1, 100);
        const agencySql = searchQuery(AGENCY, {}, 1, 100);
        const modelData = await ctx.app.mysql.query(modelSql.sqlQuery);
        const agencyData = await ctx.app.mysql.query(agencySql.sqlQuery);
        const countObj = await ctx.app.mysql.query(sqlCount);
        const newData = data.map(item => {
            const itemData = modelData.find(model => model.id == item.model); // == 隐式类型自动转换
            const agencyItem = agencyData.find(agency => agency.id == item.agency_id)
            return {
                ...item,
                agency_name: agencyItem.name,
                model: itemData.name
            }

        })
        //const data = await ctx.app.mysql.query(`SELECT * FROM machine_warehousing WHERE SN like '%1%' and store_time > '2024-10-08' and store_time < '2024-10-09' LIMIT 0,10`)
        ctx.body = {
            status: 200,
            data: newData,
            pageNum: pageInfo.pageNum,
            pageSize: pageInfo.pageSize,
            total: countObj[0].total,
        }
    }
    async createMachineStore() {
        //新增机具入库
        const { ctx } = this
        const params = ctx.request.body || {};
        const { model, start_sn, end_sn, method } = params
        const tableName = MACHINE_MODEL;
        const modelInfo = model.split('-');
        const { sqlQuery } = searchQuery(tableName, { agency_id: modelInfo[1] }, 1, 100)
        const agencySql = searchQuery(AGENCY, { id: modelInfo[1] }, 1, 100)
        let insertData = []
        try {

            const data = await ctx.app.mysql.query(sqlQuery);//查型号的表获取 型号的名字，根据第三方机构去查询
            const agencyData = await ctx.app.mysql.query(agencySql.sqlQuery); //
            const currentTableName = MACHINE_WAREHOSING;
            if (method === 'code') {
                //输出对应机型的sn 入库的数据结构
                const requireParams = ['model', 'start_sn', 'end_sn'];
                if (!errorParams(params, requireParams)) {
                    ctx.body = {
                        status: 400,
                        msg: '缺少参数',
                    };
                    return;
                }
                insertData = typeOutput(modelInfo[0], start_sn, end_sn, { modelId: data[0].id, agency_id: agencyData[0].id })

            } else {
                //上传excal 方式
                let file = ctx.request.files[0];
                file = this.ctx.request.files[0];
                let list = new Array(0);
                const workbook = XLSX.readFile(file.filepath);
                for (const sheet in workbook.Sheets) {
                    if (workbook.Sheets.hasOwnProperty(sheet)) {
                        // 数据直接转成json格式 
                        list.push(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
                    }
                }

                const excalData = excalOutput(modelInfo[0], list[0], { modelId: data[0].id, agency_id: agencyData[0].id })
                if (excalData.isError) {
                    ctx.body = {
                        status: 500,
                        msg: '表格的SN格式不对',
                        data: excalData.errorData,
                    };
                    return;
                }
                insertData = excalData.insertData
            }
            //查库，检测库是否存在该数据
            const isCheckSNExists = await checkSNExists(insertData, ctx)
            if (isCheckSNExists.status) {
                ctx.body = {
                    status: 500,
                    msg: '库中已经存在该数据',
                    data: isCheckSNExists.data,
                };
                return;
            }
            const result = await ctx.app.mysql.insert(currentTableName, insertData);
            ctx.body = {
                status: 200,
                data: result.message,
                msg: '新增成功',
            };
        } catch (error) {
            console.log(error, 'error')
        }
    }
    //删除机具
    async deleteMachineStore() {
        const { ctx } = this;
        const body = ctx.request.body || {};
        const params = body;
        const ids = params.id; // 你的 ID 数组
        try {
            const placeholders = ids.map(() => '?').join(', ');
            const sql = `DELETE FROM ${MACHINE_WAREHOSING} WHERE id IN (${placeholders})`;
            // 执行删除操作
            const result = await ctx.app.mysql.query(sql, ids);
            ctx.body = {
                status: 200,
                data: ids,
                msg: '删除成功',
            }
        } catch (err) {
            throw err;
        }
    }
}

module.exports = HomeController
